package com.xxx.springboot.util;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.xxx.springboot.pojo.UserInfo;

/**
 * mongo操作工具类
 */
@Component
public class MongoUtil {
	
	@Autowired
    private MongoTemplate mongoTemplate;
	
	/**
	 * 插入文档
	 */
	public void save(UserInfo userInfo) {
		mongoTemplate.save(userInfo);
	}
	
	/**
	 * 查询文档
	 */
	public List<UserInfo> find(String username) {
		Query query=new Query(Criteria.where("userName").is(username));
		return mongoTemplate.find(query, UserInfo.class);
	}
	
	/**
	 * 修改文档
	 */
	public UpdateResult update(UserInfo userInfo) {
		Query query=new Query(Criteria.where("userId").is(userInfo.getUserId()));
		Update update= new Update().set("userName", userInfo.getUserName()).set("mobile", userInfo.getMobile());
		UpdateResult updateResult = mongoTemplate.updateMulti(query, update, UserInfo.class);
		return updateResult;
	}
	
	/**
	 * 删除文档
	 */
	public DeleteResult delete(int userId) {
		Query query=new Query(Criteria.where("userId").is(1));
		DeleteResult deleteResult = mongoTemplate.remove(query, UserInfo.class);
		return deleteResult;
	}

}
